package com.example.servlet;

import com.example.dao.FileInfoDaoImpl;
import com.example.model.FileInfo;
import com.example.service.FileInfoService;
import com.example.service.FileInfoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class DownloadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {

        String uuid = request.getParameter("uuid");
        FileInfoService fileInfoService = new FileInfoServiceImpl(new FileInfoDaoImpl());
        // 这里先下载一个固定的，等下把uuid传过来
        FileInfo fileInfo = fileInfoService.findByUUid(uuid);
        // 设置响应头属性值，使文件以附件形式进行下载
        response.setHeader("content-disposition", "attachment;filename=" + fileInfo.getFileOriginName());

        // 获取输入流
        String path = fileInfo.getFilePath() + "\\" + fileInfo.getUuid();
        InputStream is = null;
        try {
            is = new FileInputStream(new File(path));
            ServletOutputStream os = response.getOutputStream();
            // 复制文件
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            response.setStatus(410);
            e.printStackTrace();
        }


    }

}
